<template>
<!--  <div class="pie-chart-wrapper">-->
  <div class="chart-header" style="display: flex; justify-content: flex-end;">
      <div class="filter-controls">
        <el-select
          v-model="filterType"
          placeholder="选择统计维度"
          @change="updateChart"
          size="small"
          style="width: 150px; margin-right: 10px;"
        >
          <el-option label="按机场" value="airport" />
          <el-option label="按属性" value="property" />
          <el-option label="按状态" value="status" />
        </el-select>
        <el-button
          type="primary"
          size="small"
          @click="fetchAllData"
          :loading="loading"
          :icon="Refresh"
        >
          刷新
        </el-button>
      </div>
    </div>

    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { FlightApi } from '@/api/flight'
const filterType = ref('airport')
// 图表实例
const chartContainer = ref(null)
const chartInstance = ref(null)
const loading = ref(false)

// 数据状态
const summaryData = ref({
  total: 0,
  open: 0,
  closed: 0,
  domestic: 0,
  international: 0,
  other: 0
})

const airportCategories = ref({})

// 初始化图表
const initChart = () => {
  nextTick(() => {
    if (!chartContainer.value) return

    try {
      if (chartInstance.value) {
        chartInstance.value.dispose()
      }
      chartInstance.value = echarts.init(chartContainer.value)
      updateChart()
    } catch (err) {
      console.error('图表初始化失败:', err)
      ElMessage.error('图表初始化失败')
    }
  })
}

// 更新图表配置
const updateChart = () => {
  if (!chartInstance.value) return

  const option = {
    title: {
      text: getChartTitle(),
      left: 'center',
      top: 5,
      textStyle: {
        fontSize: 12
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },

    series: [{
      name: getSeriesName(),
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '50%'],
      roseType: 'radius',
      itemStyle: {
        borderRadius: 5,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}: {c} ({d}%)'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      data: getChartData()
    }]
  }

  chartInstance.value.setOption(option)
}

// 辅助函数
const getChartTitle = () => {
  return {
    status: '机场状态分布',
    property: '机场属性分布',
    airport: '机场分类统计 (Top 10)'
  }[filterType.value]
}

const getSeriesName = () => {
  return {
    status: '机场状态',
    property: '机场属性',
    airport: '机场分类'
  }[filterType.value]
}

const getChartData = () => {
  if (filterType.value === 'status') {
    return [
      { value: summaryData.value.open, name: '开启', itemStyle: { color: '#67C23A' } },
      { value: summaryData.value.closed, name: '关闭', itemStyle: { color: '#F56C6C' } }
    ]
  }

  if (filterType.value === 'property') {
    return [
      { value: summaryData.value.domestic, name: '国内机场', itemStyle: { color: '#36bada' } },
      { value: summaryData.value.international, name: '国际机场', itemStyle: { color: '#E6A23C' } },
      { value: summaryData.value.other, name: '其他属性', itemStyle: { color: '#6a98f3' } }
    ]
  }

  return getAirportChartData()
}
//
// const getAirportLegendData = () => {
//   const sorted = Object.entries(airportCategories.value)
//     .sort((a, b) => b[1] - a[1])
//     .slice(0, 10)
//   const otherCount = Object.values(airportCategories.value)
//     .reduce((sum, count, idx) => (idx >= 10 ? sum + count : sum), 0)
//
//   return [
//     ...sorted.map(([name]) => name),
//     ...(otherCount > 0 ? ['其他机场'] : [])
//   ]
// }

const getAirportChartData = () => {
  const sorted = Object.entries(airportCategories.value)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10)
  const otherCount = Object.values(airportCategories.value)
    .reduce((sum, count, idx) => (idx >= 10 ? sum + count : sum), 0)

  return [
    ...sorted.map(([name, value]) => ({
      name,
      value,
      itemStyle: { color: getRandomColor() }
    })),
    ...(otherCount > 0
      ? [{ name: '其他机场', value: otherCount, itemStyle: { color: '#3a8ee6' } }]
      : [])
  ]
}

const getRandomColor = () => {
  return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')
}

// 数据获取
const fetchAllData = async () => {
  try {
    loading.value = true
    let allData = []
    let page = 1
    const pageSize = 100
    let hasMore = true

    while (hasMore) {
      const response = await FlightApi.getAirports(page, pageSize)
      if (response.data?.length > 0) {
        allData = [...allData, ...response.data]
        hasMore = response.data.length >= pageSize
        page++
      } else {
        hasMore = false
      }
    }

    processData(allData)
  } catch (err) {
    console.error('数据加载失败:', err)
    ElMessage.error('数据加载失败: ' + (err.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 数据处理
const processData = (data) => {
  if (!data?.length) {
    ElMessage.warning('无有效数据')
    return
  }

  const normalizedData = data.map(item => ({
    ...item,
    APOT_AISO: item.APOT_AISO === 'O' ? '0' : item.APOT_AISO
  }))

  summaryData.value = {
    total: normalizedData.length,
    open: normalizedData.filter(item => item.APOT_AISO === '0').length,
    closed: normalizedData.filter(item => item.APOT_AISO === '1').length,
    domestic: normalizedData.filter(item => item.APOT_APAT === '2403').length,
    international: normalizedData.filter(item => item.APOT_APAT === '2401').length,
    other: normalizedData.filter(item => !['2401', '2403'].includes(item.APOT_APAT)).length
  }

  airportCategories.value = normalizedData.reduce((acc, item) => {
    const name = item.APOT_CNNM || '未知机场'
    acc[name] = (acc[name] || 0) + 1
    return acc
  }, {})

  updateChart()
}

// 窗口大小调整
const handleResize = () => {
  chartInstance.value?.resize()
}

// 生命周期
onMounted(() => {
  initChart()
  fetchAllData()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance.value?.dispose()
})

// 暴露方法
defineExpose({
  refreshData: fetchAllData
})
</script>

<style scoped>
.pie-chart-wrapper {
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.filter-controls {
  display: flex;
  align-items: center;
}

@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .filter-controls {
    width: 100%;
  }
}
</style>
